package com.chen.authority.common.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chen.authority.common.constant.SysConstant;
import com.chen.authority.common.util.SaTokenUtil;
import com.chen.authority.common.model.Po;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * mybatis-plus注入处理器
 *
 * @author chengy
 * @date 2022/09/04
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof Po) {
            Po po = (Po) metaObject.getOriginalObject();
            Date current = ObjectUtil.isNotNull(po.getCreateTime()) ? po.getCreateTime() : new Date();
            po.setCreateTime(current);
            po.setUpdateTime(current);
            String createBy = po.getCreateBy();
            String username = StringUtils.isBlank(createBy) ? SaTokenUtil.getLoginUsername() : createBy;
            po.setCreateBy(username);
            po.setUpdateBy(username);
            po.setVersion(SysConstant.INIT_VERSION);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof Po) {
            Po po = (Po) metaObject.getOriginalObject();
            po.setUpdateTime(new Date());
            String username = SaTokenUtil.getLoginUsername();
            if (StringUtils.isNotBlank(username)) {
                po.setUpdateBy(username);
            }
        }
    }

}
